package com.txy;

import com.txy.pojo.MonitorData;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Monitor implements Runnable {
    private static Monitor instance = new Monitor();

    public static Monitor getInstance() {
        return instance;
    }

    public final Map<String, List<MonitorData>> method2CostMap = new ConcurrentHashMap<>();


    public Monitor() {
        Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(this, 1, 5, TimeUnit.SECONDS);
    }

    public void put(String methodName, Long costTime) {
        if (Monitor.getInstance().method2CostMap.get(methodName) == null) {
            Monitor.getInstance().method2CostMap.put(methodName, new ArrayList<>());
        }
        Monitor.getInstance().method2CostMap.get(methodName).add(new MonitorData(costTime));
//        System.out.println();
    }


    @Override
    public void run() {
        if (Monitor.getInstance().method2CostMap.isEmpty()) {
            System.out.println("***** " + Monitor.getInstance() + " 空");
        } else {
            for (Map.Entry<String, List<MonitorData>> entry : Monitor.getInstance().method2CostMap.entrySet()) {
                String methodName = entry.getKey();
                if (entry.getValue() != null && !entry.getValue().isEmpty()) {

                    Long[] costList = getCostArray(entry.getValue());
                    Arrays.sort(costList);
                    long tp90 = costList[(int) (costList.length * 0.9)];
                    long tp99 = costList[Math.min(costList.length - 1, (int) (costList.length * 0.99))];
                    System.out.print("***** 最近1分钟内:" + methodName + "总数" + costList.length + " tp90=" + tp90 + " tp99=" + tp99 + " *****");
                }
            }
            System.out.println();
        }
    }

    // 统计最近1分钟内的
    private Long[] getCostArray(List<MonitorData> list) {
        List<Long> tmpList = new ArrayList<>();
        long oneMinuteAgo = System.currentTimeMillis() - 60*1000;
        for (MonitorData monitorData : list) {
            if(monitorData.getTimestamp()>oneMinuteAgo) {
                tmpList.add(monitorData.getCostTime());
            }
        }
        Long[] arr = new Long[tmpList.size()];
        for(int i = 0;i<tmpList.size();i++) {
            arr[i] = tmpList.get(i);
        }
        return arr;
    }
}
